import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { STComponent, STColumn, STRequestOptions, STChange, STData } from '@delon/abc/st';
import { SFComponent, SFSchema, SFDateWidgetSchema } from '@delon/form';
import { SearchDrawerService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { BasicTableComponent } from 'src/app/routes/commom';
import { FreightAccountService } from '../../services/freight-account.service';

@Component({
  selector: 'app-refund-record',
  templateUrl: './refund-record.component.html',
  styleUrls: ['../../../commom/less/commom-table.less']
})
export class RefundRecordComponent extends BasicTableComponent implements OnInit {
  @ViewChild('auditModal', { static: false })
  auditModal!: any;
  columns: STColumn[] = this.initST();
  schema: SFSchema = this.initSF();

  refundStatus: any = '';

  msg = '';

  constructor(
    public service: FreightAccountService,
    private nzModalService: NzModalService,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
  }

  ngOnInit(): void {}
  search() {
    this.st?.load(1);
  }

  beforeReq = (requestOptions: STRequestOptions) => {
    Object.assign(requestOptions.body, { refundStatus: this.refundStatus || null });
    if (this.sf) {
      Object.assign(requestOptions.body, {
        ...this.sf?.value,
        refundExecuteTime: {
          start: this.sf?.value.refundExecuteTime?.[0] || '',
          end: this.sf?.value.refundExecuteTime?.[1] || ''
        }
      });
    }
    return requestOptions;
  };

  changeRefundStatus(status?: string) {
    this.refundStatus = status || null;
    this.st.load(1);
  }

  auditAction(item?: any) {
    this.msg = '';
    const modal = this.nzModalService.create({
      nzTitle: '审核',
      nzContent: this.auditModal,
      nzFooter: [
        {
          label: '拒绝',
          type: 'default',
          loading: () => this.service.http.loading,
          onClick: () => {
            if (!this.msg) {
              this.service.msgSrv.warning('请填写原因');
              return false;
            }
            this.service
              .request(this.service.$api_disagree_refund_record, {
                applicationId: item.id,
                remark: this.msg
              })
              .subscribe(res => {
                if (res) {
                  this.service.msgSrv.success('审核拒绝成功');
                  modal.destroy(true);
                  this.st.load(1);
                }
              });
            return false;
          }
        },
        {
          label: '通过',
          type: 'primary',
          loading: () => this.service.http.loading,
          onClick: () => {
            this.service
              .request(this.service.$api_agree_refund_record, {
                applicationId: item.id,
                remark: this.msg
              })
              .subscribe(res => {
                if (res) {
                  this.service.msgSrv.success('审核通过成功');
                  modal.destroy(true);
                  this.st.load(1);
                }
              });
            return false;
          }
        }
      ]
    });
  }

  reApply(item: any) {
    const modal = this.nzModalService.warning({
      nzTitle: '确定要重新发起退款？',
      nzOnOk: () => {
        this.service
          .request(this.service.$api_rebulid_refund_record, {
            applicationId: item.id
          })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success('发起成功');
              modal.destroy(true);
              this.st.load(1);
            }
          });
        return false;
      }
    });
  }

  private initSF(): SFSchema {
    return {
      properties: {
        expand: {
          type: 'boolean',
          ui: {
            hidden: true
          }
        },
        orderRefundCode: {
          type: 'string',
          title: '退款单号',
          ui: {
            placeholder: '请输入'
          }
        },
        refundType: {
          type: 'string',
          title: '退款类型',
          enum: [
            { value: '1', label: '平台退款货主' },
            { value: '2', label: '司机退款平台' },
            { value: '3', label: '车队长退款司机' },
            { value: '4', label: '车队长退款平台' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择'
          }
        },
        enterpriseInfoName: {
          type: 'string',
          title: '货主',
          ui: {
            placeholder: '请输入'
          }
        },
        billCode: {
          type: 'string',
          title: '订单号',
          ui: {
            placeholder: '请输入'
          }
        },
        captainName: {
          type: 'string',
          title: '收款人',
          ui: {
            placeholder: '请输入'
          }
        },
        enterpriseProjectName: {
          type: 'string',
          title: '所属项目',
          ui: {
            placeholder: '请输入'
          }
        },
        resourceCode: {
          type: 'string',
          title: '货源号',
          ui: {
            placeholder: '请输入'
          }
        },
        refundExecuteTime: {
          title: '退款时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            nzShowTime: true
          } as SFDateWidgetSchema
        },
        ltdId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.service.getNetworkFreightForwarder()
          }
        },
        bankType: {
          type: 'string',
          title: '银行类型',
          ui: {
            widget: 'dict-select',
            params: { dictKey: 'bankname:type' },
            placeholder: '请输入'
          }
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return ((this.st.pi -1) * this.st.ps) + idx + 1 + ''
        } 
      },
      { title: '退款单号', render: 'orderRefundCode', width: 190 },
      { title: '退款类型', index: 'refundTypeLabel', width: 140 },
      { title: '退款金额', render: 'refundAmount', className: 'text-right', width: 180 },
      {
        title: '合计金额',
        index: 'refundAmount',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.refundAmount }) }
      },
      { title: '退款时间', index: 'refundExecuteTime', width: 170 },
      { title: '货主', index: 'enterpriseInfoName', width: 150 },
      { title: '所属项目', index: 'enterpriseProjectName', width: 140 },
      { title: '支付单', render: 'billRefundPaymentVOS', width: 150 },
      { title: '订单号', index: 'billCode', width: 150 },
      { title: '货源号', index: 'resourceCode', width: 150 },
      { title: '司机', render: 'driver', width: 150 },
      { title: '收款人', render: 'captain', width: 150 },
      { title: '网络货运人', index: 'ltdName', width: 180 },
      { title: '银行类型', index: 'bankTypeLabel', width: 120 },
      { title: '退款原因', index: 'reason', width: 170 },
      { title: '失败原因', index: 'failCause', width: 170 },
      {
        title: '操作',
        fixed: 'right',
        className: 'text-center',
        width: '150px',
        buttons: [
          {
            text: '审核',
            iif: item => item.refundStatus === '1',
            click: item => this.auditAction(item)
          },
          {
            text: '重新发起',
            iif: item => item.refundStatus === '5',
            click: item => this.reApply(item)
          }
          // {
          //   text: '关闭',
          //   click: item => this.router.navigate(['/financial-management/withdrawals-record/detail/' + item.id])
          // }
        ]
      }
    ];
  }
  // 导出
  exprot() {
    this.service.exportStart({ ...this.sf?.value, pageSize: -1 }, this.service.$api_get_asyncExportBillRefundApplicationList);
  }
}
